package com.ph.clouds.tracker.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @Author yushuangjiang
 * @Time 2021/8/2 14:52
 * @Description： 埋点事件记录表 创建数据库 版本升级等
 */
public class TrackDatabaseHelper extends SQLiteOpenHelper {
    private static TrackDatabaseHelper helper;
    private static SQLiteDatabase database;
    public static final Object dbSync = new Object();

    public static TrackDatabaseHelper getInstance(Context context) {
        if (helper == null) {
            synchronized (dbSync) {
                if (helper == null) {
                    helper = new TrackDatabaseHelper(context.getApplicationContext());
                }
            }
        }
        return helper;
    }

    private static final String CREATE_EVENTS = "CREATE TABLE " + DataBaseColumns.TABLE_NAME
            + " (id integer primary key autoincrement, "
            + DataBaseColumns.PAGE_ID + " TEXT ,"
            + DataBaseColumns.EVENTS_ID + " TEXT ,"
            + DataBaseColumns.EVENTS_ALIAS + " TEXT , "
            + DataBaseColumns.EVENTS_CREATOR + " TEXT , "
            + DataBaseColumns.EVENTS_STATUE + " INTEGER ,"
            + DataBaseColumns.EVENTS_CREATE_TIME + " TEXT,"
            + DataBaseColumns.EVENTS_END_TIME + " TEXT"
            + ");";

    public TrackDatabaseHelper(Context context) {
        super(context, DataBaseColumns.EVENT_DATABASE_NAME, null, DataBaseColumns.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(CREATE_EVENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DataBaseColumns.TABLE_NAME);
        onCreate(db);
    }

    @Override
    public synchronized void close() {
        if (database != null) {
            database.close();
            database = null;
        }
        super.close();
    }
}